package com.onec.service.route.service.impl;

import cn.hutool.core.date.DateUtil;
import com.onec.service.api.enums.SystemTypeEnum;
import com.onec.service.route.dao.AgentLimitRepository;
import com.onec.service.route.entity.AgentLimitInfo;
import com.onec.service.route.service.AgentLimitInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @author onec
 * @see
 */
@Service
public class AgentLimitInfoServiceImpl implements AgentLimitInfoService {

    @Autowired
    AgentLimitRepository agentLimitRepository;

    @Override
    public AgentLimitInfo findAgentAgentCodeTypeValue(String agentCode, SystemTypeEnum typeEnum, String value) {
        return agentLimitRepository.findByAgentCodeAndTypeAndValue(agentCode, typeEnum, value);
    }

    /**
     * 验证机构限制是否可以通过：
     *
     * @param agentCode
     * @param typeEnum
     * @param value
     * @param param
     * @return
     */
    @Override
    public boolean isOk(String agentCode, SystemTypeEnum typeEnum, String value, Integer param) {
        AgentLimitInfo agentLimitInfo = this.findAgentAgentCodeTypeValue(agentCode, typeEnum, value);
        if (Optional.ofNullable(agentLimitInfo).isEmpty()) {
            return true;
        }
        if (agentLimitInfo.getTotalSize() < param) {
            return true;
        }
        return false;
    }

    /**
     * 新增机构限制：如果存在修改数据：+1 ：不存在：新增数据：默认：1
     *
     * @param agentCode
     * @param typeEnum
     * @param value
     */
    @Override
    public void addAgentInfoLimit(String agentCode, SystemTypeEnum typeEnum, String value) {
        AgentLimitInfo agentLimitInfo = agentLimitRepository
                .findByAgentCodeAndTypeAndValue(agentCode, typeEnum, value);
        if (Optional.ofNullable(agentLimitInfo).isEmpty()) {
            agentLimitInfo = new AgentLimitInfo();
            agentLimitInfo.setAgentCode(agentCode);
            agentLimitInfo.setSize(0);
            agentLimitInfo.setTotalSize(0);
            agentLimitInfo.setType(typeEnum);
            agentLimitInfo.setValue(value);
        }
        agentLimitInfo.setTotalSize(agentLimitInfo.getTotalSize() + 1);
        agentLimitInfo.setUpdateTime(DateUtil.date());
        agentLimitRepository.save(agentLimitInfo);
    }


}
